package com.uzai.console.service.tb.tbtoken.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.common.enums.SysMsgTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.CommonUtil;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.tb.tbtoken.TbTokenCallBackDto;
import com.uzai.console.entity.Merchant;
import com.uzai.console.entity.TbRidToken;
import com.uzai.console.entity.TbToken;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.mapper.TbRidTokenMapper;
import com.uzai.console.mapper.TbTokenMapper;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.tb.tbridpid.TbRidPidService;
import com.uzai.console.service.tb.tbtoken.TbTokenCallBackService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @author liuqi
 * @date 2021年08月31日 20:10
 */
@Service
public class TbTokenCallBackServiceImpl implements TbTokenCallBackService {

    private Logger logger = LoggerFactory.getLogger(TbTokenCallBackServiceImpl.class);

    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private TbRidTokenMapper tbRidTokenMapper;
    @Autowired
    private TbRidPidService tbRidPidService;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    @Transactional
    @Override
    public void add(TbToken tbToken) {
        Merchant merchant = merchantMapper.selectById(tbToken.getMerId());
        if (merchant==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "没有该运营商");
        }
        TbToken at = tbTokenMapper.selectByUserIdAndTurnLink(tbToken.getUserId(), tbToken.getTurnlink());
        //该淘宝联盟账号不存在，则新增加
        if (at == null){
            tbTokenMapper.insertSelective(tbToken);

            //发送其他异常提醒
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(merchant.getId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OTHER_EXCEPTION.getValue()); //其他异常提醒
            //消息
            JSONObject ext = new JSONObject();
            StringBuilder content = new StringBuilder();
            content.append("淘宝已增加联盟授权，账号").append(tbToken.getUserName());
            //当前操作员
            ext.put("content", content.toString());
            ext.put("phone", merchant.getMobile());
            ext.put("errorcode", content.toString());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---淘宝添加联盟授权，发送其他异常消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }else{
            if(at.getType().intValue() != tbToken.getType().intValue()){//验证type是否一样，不一样即淘宝和饿了么共有
                tbToken.setType(2); //2-淘宝和饿了么共有
            }
            logger.info(at.getMerId() + "::" + tbToken.getMerId());
            if (at.getMerId().longValue() != tbToken.getMerId().longValue()){
                Merchant merchant1 = merchantMapper.selectById(at.getMerId());
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.ALIMM_ACCOUNT_EXIST, CommonUtil.mobileFormat(merchant1.getMobile())));
            }
            tbToken.setId(at.getId());
            tbToken.setVersion(at.getVersion());
            int count = tbTokenMapper.updateSelective(tbToken);
            if (count != 1){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.NET_ERROR);
            }
        }
    }

    //处理买家身份的饿了么联盟
    private void addTbRidToken(TbRidToken tbRidToken) {
        TbRidToken at = tbRidTokenMapper.selectByUserId(tbRidToken.getUserId());
        //该淘宝联盟账号不存在，则新增加
        if (at == null){
            tbRidTokenMapper.insertSelective(tbRidToken);
        }else{ //存在修改
            tbRidToken.setId(at.getId());
            tbRidTokenMapper.updateById(tbRidToken);
        }
    }

    @Transactional
    @Override
    public void oauth(TbTokenCallBackDto tbTokenCallBackDto){

        if(StringUtils.isBlank(tbTokenCallBackDto.getTokenInfo())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "授权信息不能为空");
        }
        Map<String,Object> tokenVo = JSONObject.parseObject(tbTokenCallBackDto.getTokenInfo(), Map.class);
        if (tokenVo.get("error") != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, tokenVo.get("error").toString());
        }

        String state = tbTokenCallBackDto.getState();
        if(StringUtils.isBlank(state)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "自定义参数不能为空");
        }

        if(StringUtils.isBlank(tbTokenCallBackDto.getTokenInfo())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "token数据不能为空");
        }

        try{

            //获取系统版本
            String version = state.substring(0,2);
            //去掉前面2位版本号，为merId_type拼凑的参数
            state = state.substring(2);

            //新建token
            int now = DateUtil.getNowTime();
            TbToken tbToken = new TbToken();
            tbToken.setUserName(URLDecoder.decode(tokenVo.get("taobao_user_nick").toString(),"UTF-8"));
            tbToken.setUserId(Long.valueOf(tokenVo.get("taobao_user_id").toString()));
            tbToken.setAccessToken(tokenVo.get("access_token").toString());
            tbToken.setRefreshToken(tokenVo.get("refresh_token").toString());
            tbToken.setExpiresin(Integer.parseInt(tokenVo.get("expires_in").toString()));
            tbToken.setReExpiresin(Integer.parseInt(tokenVo.get("re_expires_in").toString()));
            tbToken.setAuthTime(now);
            tbToken.setCreateTime(now);
            tbToken.setUpdateTime(now);
            tbToken.setExptime(now+tbToken.getExpiresin());

            //3.0系统调用授权
            if("v3".equals(version)){
                //state 为merId_type拼凑的参数
                String[] stateArr = state.split("_");
                if(stateArr == null || stateArr.length != 2){
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "自定义参数格式不正确");
                }

                if(Integer.parseInt(stateArr[1]) == 2){ //买家身份的饿了么授权
                    TbRidToken tbRidToken = new TbRidToken();
                    tbRidToken.setId(IdWorker.getId());
                    tbRidToken.setAccessToken(tbToken.getAccessToken());
                    tbRidToken.setUserId(String.valueOf(tbToken.getUserId()));
                    tbRidToken.setExptime(tbToken.getExptime());
                    tbRidToken.setCreateTime(tbToken.getCreateTime());
                    tbRidToken.setUpdateTime(tbToken.getUpdateTime());
                    addTbRidToken(tbRidToken);

                    //判断是否新增加饿了么联盟，如果是，还得增加rid-pid关系表
                    //异步执行增加pid-rid关系表
                    //暂时屏蔽掉，因为过大查询数，会消耗内存，造成宕机，如果开启，则需要分页处理
                    //tbRidPidService.addTbRidPidByTokenAdd(tbRidToken);

                }else{ //正常的淘宝或者饿了么联盟
                    tbToken.setId(IdWorker.getId());
                    //merId
                    tbToken.setMerId(Long.parseLong(stateArr[0]));
                    //类型
                    if(Integer.parseInt(stateArr[1]) == 3){
                        tbToken.setType(0); //淘宝联盟
                    }else{
                        tbToken.setType(Integer.parseInt(stateArr[1]));
                    }

                    if(Integer.parseInt(stateArr[1]) == 3){ //导购联盟
                        tbToken.setTurnlink(1);
                    }else{ //返利联盟
                        tbToken.setTurnlink(0);
                    }
                    //调用token保存方法
                    add(tbToken);
                }
            }else { //2.0系统调用授权，则刷新授权
                TbToken tbToken_old = tbTokenMapper.selectByUserIdAndTurnLink(tbToken.getUserId(), 0); //2.0默认为返利联盟
                if(tbToken_old != null){//刷新授权
                    tbToken_old.setUserName(URLDecoder.decode(tokenVo.get("taobao_user_nick").toString(),"UTF-8"));
                    tbToken_old.setAccessToken(tokenVo.get("access_token").toString());
                    tbToken_old.setRefreshToken(tokenVo.get("refresh_token").toString());
                    tbToken_old.setExpiresin(Integer.parseInt(tokenVo.get("expires_in").toString()));
                    tbToken_old.setReExpiresin(Integer.parseInt(tokenVo.get("re_expires_in").toString()));
                    tbToken_old.setAuthTime(now);
                    tbToken_old.setUpdateTime(now);
                    tbToken_old.setExptime(now+tbToken.getExpiresin());
                    tbTokenMapper.update(tbToken_old);
                }
            }
        }catch(Exception e){
            logger.error("----解析淘宝联盟token错误---error={}", e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, e.getMessage());
        }
    }

}
